/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.model;


import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.MatchArg;
import org.mybeans.factory.RollbackException;
import org.mybeans.dao.GenericDAO;
import org.mybeans.factory.Transaction;

import scheduler.databean.Bookmark;

import scheduler.model.BookmarkDao;

public class BookmarkDaoBeanFactoryImpl
    extends GenericDAO<Bookmark> 
    implements BookmarkDao { 
	
    public BookmarkDaoBeanFactoryImpl(String dbDriver, String dbUrl) {
        this(BeanTable.getSQLInstance(Bookmark.class, "bookmarks", dbDriver, dbUrl));
    }
    
    private BookmarkDaoBeanFactoryImpl(BeanTable<Bookmark> table) {
        super(table, "id");
        getTable().setIdleConnectionCleanup(true);
        setUseAutoIncrementOnCreate(true);
    }
    
    public Bookmark[] getBookmarksForUser(String userName) throws DAOException {
        try {
            return getFactory().match(MatchArg.equals("owner", userName));
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public Bookmark create() throws DAOException {
        try {
            return getFactory().create();
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public Bookmark create(String userName, String bookmarkName, String url, String comment)
        throws DAOException {
        try {
            Transaction.begin();
            Bookmark newBookmark = create();
            newBookmark.setUrl(url);
            newBookmark.setName(bookmarkName);
            newBookmark.setComment(comment);
            newBookmark.setOwner(userName);
            Transaction.commit();
            return newBookmark;
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public Bookmark lookup(int id) throws DAOException {
        try {
            return getFactory().lookup(id);
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public void update(int id, String comment) throws DAOException {
        try {
        	Transaction.begin();
        	Bookmark dbBookmark = lookup(id);
        	dbBookmark.setComment(comment);
			Transaction.commit();
        } catch (RollbackException e) {
            throw new DAOException(e);
        } finally {
        	if (Transaction.isActive()) Transaction.rollback();
        }
    }
    
    public void delete(int id) throws DAOException {
        try {
            getFactory().delete(id);
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
}
